#include "StdAfx.h"
#include "Client.h"
#include "GuiHandler.h"
#include <iostream>
#include "Util.h"

Client::Client(string n, const char *ipAddress, int port)
{
	log("############################################################");
	log("############################################################");
	log("Booting");
	name = n;
	gui = new GuiHandler(79,24,this);
	WSADATA wsaData;
	if( WSAStartup( MAKEWORD(2, 2), &wsaData ) != NO_ERROR )
	{
		log("Socket Initialization: Error with WSAStartup");
		WSACleanup();
		cin.get();
		exit(10);
	}
	log("WSAStartup successful");

	//Create a socket
	mySocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

	if ( mySocket == INVALID_SOCKET )
	{
		log("Socket Initialization: Error creating socket");
		WSACleanup();
		cin.get();
		exit(11);
	}
	log("Socket Created");
	ConnectToServer(ipAddress,port);
}

Client::~Client(void)
{
	delete gui;
	WSACleanup();
}

bool Client::SendData( char *buffer )
{	
	log("Sending data: " + string(buffer));
	send( mySocket, buffer, strlen( buffer ), 0 );
	return true;
}

bool Client::SendData(string s) {
	s = "[" + name + "] " + s;
	return SendData((char*)(s.c_str()));
}

bool Client::RecvData( char *buffer, int size )
{
	log("Receive data: " + string(buffer));
	int i = recv( mySocket, buffer, size, 0 );
	buffer[i] = '\0';
	if(i == -1) {
		return false;
	}
	return true;
}

bool Client::ConnectToServer( const char *ipAddress, int port )
{
	log("Connecting to server");
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_addr.s_addr = inet_addr( ipAddress );
	serverAddress.sin_port = htons( port );

	if ( connect( mySocket, (SOCKADDR*) &serverAddress, sizeof( serverAddress ) ) == SOCKET_ERROR )
	{
		log("ClientSocket: Failed to connect");
		WSACleanup();
		exit(11);
	}
	log("Connected");

	//Send My Name To Server
	SendData((char*)name.c_str());

	//START THREAD
	start();
	return true;
}

string Client::getName() {
	return name;
}

void Client::start() {
	char* recMessage = new char[256];	
	while(true) {

		bool b = RecvData(recMessage,256);
		if(b) {
			string c(recMessage);
			if(c.length() > 3) {
				if(c.substr(0,2) == "U:") {
					gui->printUserList(c);
				} else {
					gui->myPrint(c);
				}
			} else {
				gui->myPrint(c);
			}
		} else {
			gui->myPrint("Disconnected from server");
			gui->myPrint("Shutting down in 2 sek");
			Sleep(2000);
			exit(0);
		}
	}
	delete[] recMessage;
}

void Client::log(string s) {
	Util::printToFile("ClientLog(" + Util::getCurrentDate() + ").txt","[" + Util::getTimeStamp(false) + "] " + s);
}